package com.shanghaionstar.mro.VechileStatusCheck;

import android.os.Bundle;
import android.support.annotation.StringRes;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.PreferencesUtls;
import com.onstar.cn.framework.utils.GsonHelper;
import com.onstar.cn.vehicle.entity.DiagnosticElement;
import com.onstar.cn.vehicle.response.DiagnosticResponse;
import com.shanghaionstar.R;
import com.shanghaionstar.carmanage.iview.ICarStatusView;
import com.shanghaionstar.home.model.DiagnosticResponses;
import com.shanghaionstar.mro.MrOActivity;
import com.shanghaionstar.mro.MrOBaseFragment;
import com.shanghaionstar.utils.DateFormatUtil;
import com.shanghaionstar.utils.FinalConfigParams;
import com.shanghaionstar.utils.TextViewUtil;
import com.shanghaionstar.weight.DialPlateViewBlue;
import com.shanghaionstar.weight.PsiView;

import java.util.List;

/**
 * 小O查询车况数据
 * <p>
 * Created by Yonglang Hong on 2016/12/30.
 */
public class MrOVechileDataFragment extends MrOBaseFragment {

    private LinearLayout llContent;

    public static final int LEFT = 0;
    public static final int RIGHT = 1;

    /**
     * 小O查询车况工具类
     */
    private MrOVechileStatusQueryUtil queryUtil;

    private String type;

    private String completeTime = "2016-08-02T02:21:35.003Z";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mro_vechiledata, container, false);
        llContent = (LinearLayout) view.findViewById(R.id.ll_content);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        init();
    }

    private void init() {
        log.d("init MrOVechileDataFragment");
        showQueryMsgAndDoOrder();
    }

    /**
     * for test
     */
    private void test() {
        String content = "";
        DiagnosticResponses carStatus = GsonHelper.fromJson(content, DiagnosticResponses.class);
        showCarStatusByType(carStatus.getDiagnosticResponse());
    }

    /**
     * 显示用户输入的语句命令以及执行
     */
    private void showQueryMsgAndDoOrder() {
        Bundle bundle = getArguments();
        if (bundle != null) {
//            String msg = bundle.getString("msg");
//            addChatView(RIGHT,msg);
            type = bundle.getString("type");
            doMroOrder(type);
        }
    }

    /**
     * 查询车况
     *
     * @param type
     */
    private void doMroOrder(String type) {
        getQueryUtil().query(type);
    }

    private void addChatView(int oriention, @StringRes int msgId) {
        if (baseActivity == null || baseActivity.isFinishing())
            return;
        String msg = getString(msgId);
        addChatView(oriention, msg);
    }

    /**
     * 添加对话view
     */
    private void addChatView(int oriention, String msg) {
        if (TextUtils.isEmpty(msg))
            return;

        TextView textView = (TextView) LayoutInflater.from(getContext()).inflate(R.layout.chat_view, null);
        textView.setText(msg);

        int marginH = getResources().getDimensionPixelSize(R.dimen.dp_3);
        int marginV = getResources().getDimensionPixelSize(R.dimen.dp_10);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.setMargins(marginH, marginV, marginH, 0);

        switch (oriention) {
            case LEFT:
                textView.setTextAppearance(getContext(), R.style.mro_float_conversation_left);
                break;
            case RIGHT:
                textView.setTextAppearance(getContext(), R.style.mro_float_conversation_right);
                break;
        }

        textView.setLayoutParams(params);
        llContent.addView(textView);
    }

    private void addResultView(View view) {
        int marginV = getResources().getDimensionPixelSize(R.dimen.dp_10);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.setMargins(marginV, marginV, marginV, marginV);
        params.gravity = Gravity.CENTER_HORIZONTAL;
        llContent.addView(view, params);
    }

    public MrOVechileStatusQueryUtil getQueryUtil() {
        if (queryUtil == null) {
            queryUtil = new MrOVechileStatusQueryUtil((MrOActivity) getActivity());
            queryUtil.setCarStatusView(new ICarStatusView() {
                @Override
                public void showCarStatus(DiagnosticResponses carStatus) {
                    showCarStatusByType(carStatus.getDiagnosticResponse());
                }

                @Override
                public void showNoData() {
                    addChatView(LEFT, R.string.get_vehicle_data_failed);
                }

                @Override
                public void showOnErr(Throwable throwable) {
                    if (baseActivity == null || baseActivity.isFinishing())
                        return;
                    String msg = getString(R.string.get_vehicle_data_failed);
                    if (throwable != null && throwable.getMessage() != null) {
                        Log.d("showOnErr", throwable.getMessage());
                        msg = throwable.getMessage();
                    }
                    addChatView(LEFT, msg);
                }

                @Override
                public void showCompleteTime(String time) {
                    completeTime = time;
                    if (CommonUtil.isNull(completeTime))
                        return;
                    completeTime = DateFormatUtil.formatCST(completeTime, 8);
                }

                @Override
                public void showLoding() {
                    addChatView(LEFT, R.string.getting_vehicle_data);
                }
            });
        }
        return queryUtil;
    }

    private void showUpdateTime(View view) {
        if (CommonUtil.isNull(completeTime))
            return;
        TextView textView = (TextView) view.findViewById(R.id.tv_updateTime);
        String updateTime = getString(R.string.not_condition_data_time) + completeTime;
        textView.setText(updateTime);
    }

    private void showCarStatusByType(List<DiagnosticResponse> diagnosticResponses) {
        switch (type) {
            case "pressurequery":
                showPsi(diagnosticResponses);
                break;
            case "oilquery":
                showFuelCarStatus(diagnosticResponses, "FUEL TANK INFO");
                break;
            case "oillifequery":
                showFuelCarStatus(diagnosticResponses, "OIL LIFE");
                break;
            case "mileagequery":
                showFuelCarStatus(diagnosticResponses, "ODOMETER");
                break;
        }
    }

    private void showPsi(List<DiagnosticResponse> diagnosticResponses) {
        for (DiagnosticResponse psiBean : diagnosticResponses) {
            if (TextUtils.equals("TIRE PRESSURE", psiBean.getName())) { //胎压
                View view = LayoutInflater.from(getContext()).inflate(R.layout.mro_vechile_psi, null);
                PsiView psiView = (PsiView) view.findViewById(R.id.psiView);
                psiView.updatePsiStatus(psiBean.getDiagnosticElement());
                showUpdateTime(view);
                addChatView(LEFT, R.string.psi_as_follows);
                addResultView(view);
            }
        }
    }

    /**
     * 显示机油寿命，总里程数，燃油余量
     */
    private void showFuelCarStatus(List<DiagnosticResponse> diagnosticResponses, String vehicleType) {
        for (DiagnosticResponse responseBean : diagnosticResponses) {
            if (vehicleType.equalsIgnoreCase(responseBean.getName())) {
                switch (responseBean.getName()) {
                    case "OIL LIFE":            //机油寿命
                        setOilLife(responseBean);
                        break;
                    case "ODOMETER":            //总里程数
                        setOdoMeter(responseBean);
                        break;
                    case "FUEL TANK INFO":      //燃油余量
                        setFuelTankInfo(responseBean);
                        break;
                }
                break;
            }
        }
    }

    /**
     * 燃油余量
     */
    private void setFuelTankInfo(DiagnosticResponse responseBean) {
        List<DiagnosticElement> fuelList = responseBean.getDiagnosticElement();
        if (fuelList != null && !fuelList.isEmpty()) {
            for (DiagnosticElement elementBean : fuelList) {
                if ("FUEL LEVEL".equals(elementBean.getName().toUpperCase())) {
                    if (!TextUtils.isEmpty(elementBean.getValue())) {
                        if (CommonUtil.isNumerice(elementBean.getValue())) {
                            float fuel_value = Float.valueOf(elementBean.getValue());
                            fuel_value = Math.round(fuel_value);
                            fuel_value = fuel_value <= 0 ? 0 : fuel_value;
                            View view = LayoutInflater.from(getContext()).inflate(R.layout.mro_vechile_remainoil, null);
                            DialPlateViewBlue dialView_fuel = (DialPlateViewBlue) view.findViewById(R.id.dialView_fuel);
                            dialView_fuel.showByPercent(fuel_value / 100);
                            showUpdateTime(view);
                            addChatView(LEFT, R.string.fuel_as_follows);
                            addResultView(view);
                        }
                    }
                    break;
                }
            }
        }
    }

    /**
     * 机油寿命
     */
    private void setOilLife(DiagnosticResponse responseBean) {
        List<DiagnosticElement> oilList = responseBean.getDiagnosticElement();
        if (oilList != null && !oilList.isEmpty()) {
            DiagnosticElement oilBean = oilList.get(0);
            int oilLife = (int) Math.round(Double.valueOf(oilBean.getValue()));
            View view = LayoutInflater.from(getContext()).inflate(R.layout.mro_vechile_oillife, null);
            TextView tv_oilLife = (TextView) view.findViewById(R.id.tv_oilLife);
            tv_oilLife.setText(String.format(getString(R.string.about), oilLife + oilBean.getUnit()));
            showUpdateTime(view);
            addChatView(LEFT, R.string.oillife_as_follows);
            addResultView(view);
        }
    }

    /**
     * 总里程
     */
    private void setOdoMeter(DiagnosticResponse responseBean) {
        List<DiagnosticElement> odoList = responseBean.getDiagnosticElement();
        if (odoList != null && !odoList.isEmpty()) {
            DiagnosticElement odoBean = odoList.get(0);
            int totalMiles = Double.valueOf(odoBean.getValue()).intValue();
            View view = LayoutInflater.from(getContext()).inflate(R.layout.mro_vechile_summile, null);
            TextView tv_oilLife = (TextView) view.findViewById(R.id.tv_totalMile);
            TextViewUtil.setText(tv_oilLife,
                    String.valueOf(totalMiles),
                    String.valueOf(totalMiles) + odoBean.getUnit()
            );
            showUpdateTime(view);
            addChatView(LEFT, R.string.odometer_as_follows);
            addResultView(view);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getQueryUtil().release();
    }

    @Override
    public void onStart() {
        super.onStart();
        //标记切换到前台
        PreferencesUtls.getInstance(baseActivity).putBoolean(FinalConfigParams.MRO_VECHILE_ONSTOP, false);
    }

    @Override
    public void onStop() {
        super.onStop();
        //标记切换到后台
        PreferencesUtls.getInstance(baseActivity).putBoolean(FinalConfigParams.MRO_VECHILE_ONSTOP, true);
    }
}
